package com.paw.ruoyi.admin.controller.system;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.paw.ruoyi.admin.common.constant.CommonConstant;
import com.paw.ruoyi.admin.common.context.UserContextHolder;
import com.paw.ruoyi.admin.biz.service.SysLoginService;
import com.paw.ruoyi.admin.biz.service.SysPermissionService;
import com.paw.ruoyi.admin.biz.service.TokenService;
import com.paw.ruoyi.admin.common.AjaxResult;
import com.paw.ruoyi.admin.domain.SysMenu;
import com.paw.ruoyi.admin.domain.SysUser;
import com.paw.ruoyi.admin.domain.model.LoginBody;
import com.paw.ruoyi.admin.service.ISysMenuService;
import com.paw.ruoyi.admin.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {

  @Autowired
  private SysLoginService loginService;

  @Autowired
  private ISysMenuService menuService;

  @Autowired
  private SysPermissionService permissionService;

  @Autowired
  private ISysUserService sysUserService;

  @Autowired
  private TokenService tokenService;

  /**
   * 登录方法
   *
   * @param loginBody 登录信息
   * @return 结果
   */
  @PostMapping("/api/login")
  public AjaxResult login (@RequestBody LoginBody loginBody) {
    AjaxResult ajax = AjaxResult.success();
    // 生成令牌
    AjaxResult result = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
        loginBody.getUuid());

    return result;
  }

  /**
   * 获取用户信息
   *
   * @return 用户信息
   */
  @GetMapping("/api/getInfo")
  public AjaxResult getInfo (HttpServletRequest request) {

    SysUser user = sysUserService.selectUserById(UserContextHolder.getUserId());
    if(user==null){
      return AjaxResult.error(401,"未登录");
    }
    // 角色集合
    Set<String> roles = permissionService.getRolePermission(user);
    // 权限集合
    Set<String> permissions = permissionService.getMenuPermission(user);
    AjaxResult ajax = AjaxResult.success();
    ajax.put("user", user);
    ajax.put("roles", roles);
    ajax.put("permissions", permissions);
    tokenService.refreshToken(request.getHeader(CommonConstant.TOKEN));
    return ajax;
  }

  /**
   * 获取路由信息
   *
   * @return 路由信息
   */
  @GetMapping("/api/getRouters")
  public AjaxResult getRouters () {
    Long userId = UserContextHolder.getUserId();
    List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
    return AjaxResult.success(menuService.buildMenus(menus));
  }

  @PostMapping("/api/logout")
  public AjaxResult logout (HttpServletRequest request) {
    loginService.logout(request);
    return AjaxResult.success();
  }

}
